package com.maxsalad.eleme.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Map;

/**
 * Created by 2014-400 on 2016-03-07.
 */
public class SignUtil {
    /**
     * 拼接字符串键值对
     *
     * @param params
     * @return
     * @throws UnsupportedEncodingException
     */
    private static String concatParams(Map<String, String> params) throws UnsupportedEncodingException {
        Object[] key_arr = params.keySet().toArray();
        Arrays.sort(key_arr);

        StringBuffer buf = new StringBuffer();
        for (Object key : key_arr) {
            String val = params.get(key);
            key = URLEncoder.encode(key.toString(), "UTF-8");
            val = URLEncoder.encode(val, "UTF-8");
            buf.append("&" + key + "=" + val);
        }

        return buf.toString().replaceFirst("&", "");
    }

    /**
     * 字节数组16进制转换
     *
     * @param data
     * @return
     */
    private static String byte2hex(byte[] data) {
        StringBuffer buf = new StringBuffer();
        int i;
        for (int offset = 0; offset < data.length; offset++) {
            i = data[offset];
            if (i < 0) {
                i += 256;
            }
            if (i < 16) {
                buf.append("0");
            }
            buf.append(Integer.toHexString(i));
        }

        return buf.toString();
    }

    /**
     * 计算sign
     *
     * @param pathUrl
     * @param params
     * @param consumerSecret
     * @return
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     */
    public static String getSign(String pathUrl, Map<String, String> params, String consumerSecret) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        //不论访问的URL是否最后是以/结束，计算sig的时候都要加上末尾的/
        if (pathUrl.charAt(pathUrl.length() - 1) != '/') {
            pathUrl += "/";
        }
        String str = concatParams(params);
        str = pathUrl + "?" + str + consumerSecret;

        MessageDigest md = MessageDigest.getInstance("SHA1");
        return byte2hex(md.digest(byte2hex(str.getBytes("UTF-8")).getBytes()));
    }
}
